package com.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.Dao.DaoTest;
import com.server.Middle;
/**
 * 服务端
 * @author Administrator
 *
 */
public class SocketServer {
	
    public void startServer(){
    	ServerSocket serverSocket = null;
    	Socket socket = null;
    	int port=9898;
    	try {
			serverSocket = new ServerSocket(port);
			System.out.println("服务端已启动……");
			while(true){
				socket=serverSocket.accept();
				manageConnection(socket);
			}
		} catch (IOException e) {
			
			e.printStackTrace();
		} finally {
			try {
				socket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
    }
    public void manageConnection(final Socket socket){
    	new Thread(new Runnable() {
			@Override
			public void run() {
				BufferedReader reader = null;
				BufferedWriter writer = null;
				//DaoTest daoTest=new DaoTest();
				try {
					System.out.println("客户端："+socket.hashCode()+"已连接");
					reader=new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
					writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
					String receivedMsg;
					while((receivedMsg=reader.readLine())!=null){
						System.out.println("客户端"+socket.hashCode()+"："+receivedMsg);
						Middle middle=new Middle();
						//String data=middle.MiddleTest(receivedMsg,daoTest);
						String data="ok";
				    	if(data!=null){
				    		writer.write(data+"\n");
				    		writer.flush();
				    	}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					try {
						reader.close();
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				//关闭session
				//daoTest.closeSession();
				System.out.println("客户端："+socket.hashCode()+"已关闭");
			}
		}).start();
    }

}